package com.shanghaionstar.nav.presenter;

import com.onstar.cn.auth.userProfile.FeatureEnum;
import com.onstar.cn.common.exception.HttpException;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.framework.mvp.base.IMVPScheduler;
import com.onstar.cn.framework.mvp.base.IMVPView;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.framework.utils.RxBus;
import com.onstar.cn.mag.enumtype.RemoteCommandsType;
import com.onstar.cn.map.common.PoiItemInfo;
import com.onstar.cn.rxconstants.RxConstants;
import com.onstar.cn.vehicle.entity.ErrorInfo;
import com.shanghaionstar.OnstarApplication;
import com.shanghaionstar.R;
import com.shanghaionstar.nav.iview.INavPoiDetailView;
import com.shanghaionstar.nav.model.NavInfoModel;
import com.shanghaionstar.nav.service.AbstractMapActivity;
import com.shanghaionstar.nav.service.NavService;
import com.shanghaionstar.sqlite.SearchHistoryImpl;
import com.shanghaionstar.sqlite.TBTHistoryImpl;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.AuthorUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.ErrorCodeUtil;
import com.shanghaionstar.utils.FinalConfigParams;
import com.shanghaionstar.utils.MapHandler;
import com.shanghaionstar.utils.NavHolder;

import rx.functions.Action1;

/**
 * Created by 6335yz on 2016/7/18.
 */
public class NavPoiDetailPresenter extends BasePresenter {
    private MapHandler mapHandler;
    private AbstractMapActivity mapActivity;
    private NavService navService;
    private INavPoiDetailView navPoiDetailView;
    protected PreferencesUtls preferences = PreferencesUtls.getInstance(OnstarApplication.getApplication());

    public NavPoiDetailPresenter(IMVPScheduler mvpScheduler) {
        super(mvpScheduler);
    }

    public NavPoiDetailPresenter(IMVPScheduler mvpScheduler, AbstractMapActivity mapActivity, MapHandler mapHandler) {
        super(mvpScheduler);
        this.mapActivity = mapActivity;
        this.mapHandler = mapHandler;
        navService = new NavService(mapActivity);
        initOddBtn();
    }

    public void initOddBtn() {
        // 车载导航 ODD
        if (ApplicationUtil.getInstance().isLogin() && BusinessUtil.isServiceFeature(
                FeatureEnum.SENDNAVDESTINATION.value(), mapActivity)) {
            if (navPoiDetailView != null) {
                navPoiDetailView.showOddBtn(true);
            }
        } else {
            if (navPoiDetailView != null) {
                navPoiDetailView.showOddBtn(false);
            }
        }
    }

    @Override
    public void setView(IMVPView view) {
        super.setView(view);
        navPoiDetailView = (INavPoiDetailView) view;
    }

    public void sendTbtOrOdd(final PoiItemInfo poiItemInfo, final RemoteCommandsType remoteCommandsType) {
        if(ApplicationUtil.getInstance().isCommanding){
            ApplicationUtil.getInstance().controlCommand(mapActivity);
            return;
        }else {
            ApplicationUtil.getInstance().isCommanding = true;
        }
        if (validateTbtOrOdd(poiItemInfo, remoteCommandsType)) {
//            BusinessUtil.sendReportByClickType(mapActivity, FunctionNameFindId.POIviewTBT.getStringValue());
            NavInfoModel navInfoModel = new NavInfoModel();
            navInfoModel.remoteCommandsType = remoteCommandsType;
            navInfoModel.poiItemInfo = poiItemInfo;
            new AuthorUtil().reauthForNoPin(mapActivity, new Action1() {
                @Override
                public void call(Object o) {
                    NavInfoModel tmp = new NavInfoModel();
                    tmp.remoteCommandsType = remoteCommandsType;
                    tmp.poiItemInfo = poiItemInfo;
                    doNavCommand(tmp);
                }
            }, new Action1<Throwable>() {
                @Override
                public void call(Throwable throwable) {
                    ApplicationUtil.getInstance().isCommanding = false;
                    if (navPoiDetailView != null) {
                        ErrorInfo errorInfo = ErrorCodeUtil.getErrorInfoByHttpException(mapActivity, new HttpException("",throwable.getMessage()));
                        navPoiDetailView.onResponseError(new OnStarException("",errorInfo.getMsg()));
                    }
                }
            });
        }
    }

    private boolean validateTbtOrOdd(PoiItemInfo poiItemInfo, RemoteCommandsType remoteCommandsType) {
        if (poiItemInfo == null) return false;
        if (remoteCommandsType != RemoteCommandsType.COMMANDS_TBT_ROUTE && remoteCommandsType != RemoteCommandsType.COMMANDS_NAV_DESTINATION)
            return false;
        if (!ApplicationUtil.getInstance().isLogin())
            return false;
        if (ApplicationUtil.getInstance().isAutoLogings()) {
            if (navPoiDetailView != null) {
                navPoiDetailView.onResponseError(new OnStarException("", mapActivity.getString(R.string.loading)));
            }
        }
        if (!BusinessUtil.checkDriverOrProxyAndShowDialog(mapActivity)) {
            return false;
        }
        if (!BusinessUtil.checkPackageRight(Constants.ENTITLEMENT_M05NAVIGATION, mapActivity, true)) {
            return false;
        }
        //判断是否正在执行车辆的相关操作
        if (BusinessUtil.checkInProgressCommand(mapActivity, null, false)) {
            AlertDialogUtil.showAlertDialog(mapActivity, mapActivity.getString(R.string.dialog_warning),
                    mapActivity.getString(R.string.service_inProcess_alert));
//            BusinessUtil.updateConfigValue(FinalConfigParams.SHARE_DESTINATION, "-1", mapActivity);
            return false;
        }
        return true;
    }

    private void doNavCommand(final NavInfoModel navInfoModel) {
//        BusinessUtil.sendReportByClickType(mapActivity, FunctionNameFindId.Mytrip_Navigation.getStringValue());
        subscription = navService.doNavCommand(navInfoModel)
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String requestId) {
                        if (navInfoModel.remoteCommandsType == RemoteCommandsType.COMMANDS_NAV_DESTINATION || navInfoModel.remoteCommandsType == RemoteCommandsType.COMMANDS_TBT_ROUTE) {
                            TBTHistoryImpl tbtHistoryImpl = new TBTHistoryImpl(mapActivity);
                            SearchHistoryImpl searchHistoryImpl = new SearchHistoryImpl(mapActivity);
                            tbtHistoryImpl.saveHistoryToSql(requestId, navInfoModel.poiItemInfo, null, true);
                            //将下发历史保存到历史记录中
                            searchHistoryImpl.saveSearchHistory(navInfoModel.poiItemInfo);
                            RxBus.getDefault().post(RxConstants.ALL_PAGE_REFRESH, RxConstants.NAV_SAVE_POI);
                        }
                        if(navPoiDetailView!=null) {
                            navPoiDetailView.showCommandLoading(true);
                        }
                        NavHolder.getInstance(mapActivity).setCurrentSendPoi(navInfoModel.poiItemInfo);

                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //里面抛出的Error信息
                        if (navPoiDetailView != null) {
                            navPoiDetailView.onResponseError((OnStarException) throwable);
                        }
                    }
                });
    }

}
